#!/bin/bash

# jshERP-web Docker 部署脚本 - 支持Git代码拉取和Token认证
# 使用方法: ./deploy.sh [dev|prod] [--force]
# 注意: 此脚本需要在 deployment 目录中执行

set -e

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$SCRIPT_DIR"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color

# 项目信息
PROJECT_NAME="jshERP-web"
IMAGE_NAME="jsherp-web"
TAG=${1:-latest}

# 解析参数
ENV="dev"
FORCE_DEPLOY=false
for arg in "$@"; do
    case $arg in
        dev|prod)
            ENV=$arg
            ;;
        --force)
            FORCE_DEPLOY=true
            ;;
    esac
done

# 加载环境变量文件（如果存在）
if [ -f "$SCRIPT_DIR/.env" ]; then
    log "${BLUE}📄 加载环境变量文件: .env${NC}"
    set -a
    source "$SCRIPT_DIR/.env"
    set +a
fi

# Git配置（可通过环境变量覆盖）
GIT_REPO_URL=${GIT_REPO_URL:-"https://gitee.com/xsfcjy/JSH_ERP.git"}
GIT_BRANCH=${GIT_BRANCH:-"master"}
GIT_TOKEN=${GIT_TOKEN:-"e962dcccdb1e3384645c7c5c4c1e47c7"}
GIT_USERNAME=${GIT_USERNAME:-"xsfcjy"}

# 工作目录
BUILD_DIR=${BUILD_DIR:-"/data/source/jshERP-web/deployment/build"}
WORK_DIR="$BUILD_DIR/$PROJECT_NAME"
BACKUP_DIR="$BUILD_DIR/backup"

# 日志文件
LOG_DIR=${LOG_DIR:-"/data/source/jshERP-web/logs"}
mkdir -p "$LOG_DIR" 2>/dev/null || true
LOG_FILE="$LOG_DIR/jshERP-web-deploy-$(date +%Y%m%d_%H%M%S).log"

# 日志函数
log() {
    echo -e "$1" | tee -a "$LOG_FILE"
}

# 错误处理函数
error_exit() {
    log "${RED}❌ 错误: $1${NC}"
    exit 1
}

# 检查必需的工具
check_requirements() {
    log "${BLUE}🔍 检查部署环境...${NC}"

    # 检查Git
    if ! command -v git &> /dev/null; then
        error_exit "Git 未安装"
    fi

    # 检查Docker
    if ! docker info > /dev/null 2>&1; then
        error_exit "Docker 未运行或无法访问"
    fi

    # 检查docker-compose
    if ! command -v docker-compose &> /dev/null; then
        error_exit "docker-compose 未安装"
    fi

    # 检查Git Token
    if [ -z "$GIT_TOKEN" ]; then
        error_exit "请设置 GIT_TOKEN 环境变量"
    fi

    log "${GREEN}✅ 环境检查通过${NC}"
}

# 配置Git认证
setup_git_auth() {
    log "${BLUE}🔧 配置Git认证...${NC}"

    # 配置Git用户信息
    git config --global user.name "$GIT_USERNAME" || true
    git config --global user.email "$GIT_USERNAME@example.com" || true

    # 配置Git凭证存储
    git config --global credential.helper store || true

    # 创建Git凭证文件
    echo "https://oauth2:${GIT_TOKEN}@gitee.com" > ~/.git-credentials

    log "${GREEN}✅ Git认证配置完成${NC}"
}

# 备份当前代码
backup_current_code() {
    if [ -d "$WORK_DIR" ]; then
        log "${YELLOW}📦 备份当前代码...${NC}"
        mkdir -p "$BACKUP_DIR"
        if [ -d "$BACKUP_DIR" ]; then
            rm -rf "$BACKUP_DIR"
        fi
        cp -r "$WORK_DIR" "$BACKUP_DIR" || true
        log "${GREEN}✅ 代码备份完成${NC}"
    fi
}

# 拉取最新代码
pull_latest_code() {
    log "${BLUE}📥 拉取最新代码...${NC}"

    # 创建或清理工作目录
    if [ -d "$WORK_DIR" ]; then
        log "${YELLOW}清理工作目录...${NC}"
        rm -rf "$WORK_DIR"
    fi

    mkdir -p "$WORK_DIR"
    cd "$WORK_DIR"

    # 构造带token的Git URL
    if [[ $GIT_REPO_URL == https://gitee.com/* ]]; then
        # Gitee格式
        GIT_URL_WITH_TOKEN=$(echo $GIT_REPO_URL | sed "s|https://gitee.com/|https://oauth2:${GIT_TOKEN}@gitee.com/|")
    elif [[ $GIT_REPO_URL == https://github.com/* ]]; then
        # GitHub格式
        GIT_URL_WITH_TOKEN=$(echo $GIT_REPO_URL | sed "s|https://github.com/|https://${GIT_TOKEN}@github.com/|")
    else
        error_exit "不支持的Git仓库类型，仅支持Gitee和GitHub"
    fi

    # 克隆仓库
    log "${YELLOW}克隆仓库: $GIT_REPO_URL (分支: $GIT_BRANCH)${NC}"
    if git clone --depth 1 --branch "$GIT_BRANCH" "$GIT_URL_WITH_TOKEN" .; then
        log "${GREEN}✅ 代码拉取成功${NC}"

        # 显示提交信息
        COMMIT_HASH=$(git rev-parse --short HEAD)
        COMMIT_MSG=$(git log -1 --pretty=format:"%s")
        log "${PURPLE}📝 最新提交: $COMMIT_HASH - $COMMIT_MSG${NC}"
    else
        error_exit "代码拉取失败"
    fi
}

# 检查代码变更
check_code_changes() {
    if [ "$FORCE_DEPLOY" = true ]; then
        log "${YELLOW}⚡ 强制部署模式，跳过代码变更检查${NC}"
        return
    fi

    log "${BLUE}🔍 检查代码变更...${NC}"

    if [ -d "$BACKUP_DIR" ] && [ -d "$WORK_DIR" ]; then
        # 比较文件变更
        if diff -r "$BACKUP_DIR" "$WORK_DIR" > /dev/null 2>&1; then
            log "${YELLOW}⚠️  代码无变更，是否继续部署? (y/N)${NC}"
            read -r response
            if [[ ! "$response" =~ ^[Yy]$ ]]; then
                log "${YELLOW}部署已取消${NC}"
                exit 0
            fi
        else
            log "${GREEN}✅ 检测到代码变更${NC}"
        fi
    else
        log "${YELLOW}首次部署或无备份目录，跳过变更检查${NC}"
    fi
}

# 构建Docker镜像
build_docker_image() {
    log "${BLUE}🐳 构建Docker镜像...${NC}"

    # 切换到项目目录
    cd "$WORK_DIR/jshERP-web"

    # 检查Dockerfile是否存在
    if [ ! -f "deployment/Dockerfile" ]; then
        error_exit "Dockerfile 不存在: deployment/Dockerfile"
    fi

    # 切换到deployment目录执行构建
    cd deployment

    # 根据环境选择配置文件
    if [ "$ENV" = "prod" ]; then
        COMPOSE_FILE="docker-compose.prod.yml"
        log "${GREEN}使用生产环境配置${NC}"
    else
        COMPOSE_FILE="docker-compose.yml"
        log "${GREEN}使用开发环境配置${NC}"
    fi

    # 构建镜像
    log "${YELLOW}构建镜像: $IMAGE_NAME:$TAG${NC}"
    if docker-compose -f $COMPOSE_FILE build --no-cache; then
        log "${GREEN}✅ Docker镜像构建成功${NC}"
    else
        error_exit "Docker镜像构建失败"
    fi
}

# 部署服务
deploy_service() {
    log "${BLUE}🚀 部署服务...${NC}"

    # 切换到deployment目录
    cd "$WORK_DIR/jshERP-web/deployment"

    # 根据环境选择配置文件
    if [ "$ENV" = "prod" ]; then
        COMPOSE_FILE="docker-compose.prod.yml"
    else
        COMPOSE_FILE="docker-compose.yml"
    fi

    # 停止并删除旧容器
    log "${YELLOW}停止旧容器...${NC}"
    docker-compose -f $COMPOSE_FILE down --remove-orphans 2>/dev/null || true

    # 强制删除同名容器（如果存在）
    log "${YELLOW}清理同名容器...${NC}"
    docker rm -f jshERP-web 2>/dev/null || true

    # 清理旧镜像
    log "${YELLOW}清理旧镜像...${NC}"
    docker image prune -f

    # 启动服务
    log "${GREEN}启动服务...${NC}"
    if docker-compose -f $COMPOSE_FILE up -d; then
        log "${GREEN}✅ 服务启动成功${NC}"
    else
        error_exit "服务启动失败"
    fi
}

# 健康检查
health_check() {
    log "${BLUE}🏥 执行健康检查...${NC}"

    # 等待服务启动
    log "${YELLOW}等待服务启动...${NC}"
    sleep 10

    # 检查容器状态
    if docker ps | grep -q jshERP-web; then
        log "${GREEN}✅ 容器运行正常${NC}"
    else
        error_exit "容器启动失败"
    fi

    # HTTP健康检查
    local port=3000
    if [ "$ENV" = "prod" ]; then
        port=80
    fi

    for i in {1..10}; do
        if curl -f http://localhost:$port/ > /dev/null 2>&1; then
            log "${GREEN}✅ HTTP健康检查通过${NC}"
            break
        else
            log "${YELLOW}等待服务就绪... (${i}/10)${NC}"
            sleep 3
        fi

        if [ $i -eq 10 ]; then
            log "${YELLOW}⚠️  HTTP健康检查超时，但容器已启动${NC}"
        fi
    done
}

# 显示部署信息
show_deployment_info() {
    # 确定使用的配置文件
    local compose_file="docker-compose.yml"
    if [ "$ENV" = "prod" ]; then
        compose_file="docker-compose.prod.yml"
    fi

    log "${GREEN}🎉 部署完成!${NC}"
    log "${BLUE}================================${NC}"
    log "${YELLOW}服务信息:${NC}"
    log "  项目名称: $PROJECT_NAME"
    log "  部署环境: $ENV"
    log "  镜像标签: $TAG"
    if [ "$ENV" = "prod" ]; then
        log "  访问地址: http://localhost"
    else
        log "  访问地址: http://localhost:3000"
    fi
    log "  工作目录: $WORK_DIR"
    log "  日志文件: $LOG_FILE"
    log ""
    log "${YELLOW}常用命令:${NC}"
    log "  查看日志: cd $WORK_DIR/jshERP-web/deployment && docker-compose -f $compose_file logs -f"
    log "  停止服务: cd $WORK_DIR/jshERP-web/deployment && docker-compose -f $compose_file down"
    log "  重启服务: cd $WORK_DIR/jshERP-web/deployment && docker-compose -f $compose_file restart"
    log "  进入容器: docker exec -it jshERP-web sh"
    log "${BLUE}================================${NC}"
}

# 清理函数
cleanup() {
    log "${YELLOW}🧹 清理临时文件...${NC}"

    # 清理Git凭证
    rm -f ~/.git-credentials

    # 清理备份（保留最近3个）
    if [ -d "$BUILD_DIR/backup" ]; then
        cd "$BUILD_DIR/backup"
        ls -t | tail -n +4 | xargs -r rm -rf 2>/dev/null || true
    fi

    log "${GREEN}✅ 清理完成${NC}"
}

# 主函数
main() {
    log "${GREEN}🚀 开始部署 $PROJECT_NAME...${NC}"
    log "${YELLOW}部署环境: $ENV${NC}"
    log "${YELLOW}镜像标签: $TAG${NC}"
    log "${YELLOW}Git分支: $GIT_BRANCH${NC}"
    log "${YELLOW}日志文件: $LOG_FILE${NC}"

    # 执行部署步骤
    check_requirements
    setup_git_auth
    backup_current_code
    pull_latest_code
    check_code_changes
    build_docker_image
    deploy_service
    health_check
    show_deployment_info
    cleanup

    log "${GREEN}🎉 部署流程完成!${NC}"
}

# 信号处理
trap 'log "${RED}⚠️  部署被中断${NC}"; cleanup; exit 1' INT TERM

# 执行主函数
main "$@"

